import React from 'react';
import { ProForm, ProFormText, ProFormSelect, ProFormTextArea } from '@ant-design/pro-components';
import { Space } from 'antd';

// 定义表单字段的类型
interface PageFormValues {
  name?: string;
  type?: number;
  remark?: string;
}

interface PageFormProps {
  initialValues?: PageFormValues;
  onSubmit: any;
  columns?: any;
}

const PageForm: React.FC<PageFormProps> = ({ initialValues, onSubmit, columns }) => {
  const handleFinish = async (values: PageFormValues) => {
    if (onSubmit) {
      await onSubmit(values); // 执行父组件传入的提交方法
    }
  };

  return (
    <ProForm
      layout="vertical"
      onFinish={handleFinish}
      initialValues={initialValues}
      submitter={{
        render: (_, dom) => <Space style={{ float: 'right' }}>{dom}</Space>,
      }}
    >
      {/* 根据父组件传入的columns动态渲染表单项 */}
      {columns?.map((column: any) => {
        // 跳过操作列和隐藏的列
        if (column.dataIndex === 'action' || column.hideInForm) {
          return null;
        }

        // 根据column的component属性选择对应的表单组件
        switch (column.component) {
          case 'Select':
            return (
              <ProFormSelect
                key={column.dataIndex}
                name={column.dataIndex}
                label={column.title}
                placeholder={`请选择${column.title}`}
                options={column.componentProps?.options || []}
                rules={column.rules}
              />
            );
          case 'TextArea':
            return (
              <ProFormTextArea
                key={column.dataIndex}
                name={column.dataIndex}
                label={column.title}
                placeholder={`请输入${column.title}`}
                rules={column.rules}
              />
            );
          default:
            return (
              <ProFormText
                key={column.dataIndex}
                name={column.dataIndex}
                label={column.title}
                placeholder={`请输入${column.title}`}
                rules={column.rules}
              />
            );
        }
      })}
    </ProForm>
  );
};

export default PageForm;
